package com.sanjin.aspect;

import com.alibaba.fastjson.JSON;
import com.sanjin.annotations.SysLogOperation;
import com.sanjin.entity.Admin;
import com.sanjin.entity.SysLog;
import com.sanjin.service.SysLogService;
import com.sanjin.utils.IpAddressUtils;
import com.sanjin.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/5/9 22:02
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private SecurityUtils securityUtils;
    /**
     * 定义切点，再注释位置切入带代码
     */
    @Pointcut("@annotation(com.sanjin.annotations.SysLogOperation)")
    public void logPoint() {
    }

    /**
     * 切面，配置通知
     * @param joinPoint 织入点
     */
    @AfterReturning("logPoint()")
    public void saveSysLog(JoinPoint joinPoint) {
        log.info("[Aop切面] 记录用户操作日志");

        // 从织入点获取方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取操作
        SysLogOperation annotation = method.getAnnotation(SysLogOperation.class);

        // 获取操作描述
        String operationDescription = annotation.value();

        // 获取方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = className + "." + method.getName();

        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args);


        String username = "null";
        Admin admin = securityUtils.getAdmin();
        if (admin != null)
            username = admin.getUsername();
        // 获取请求ip地址
        String ip = "";
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();
        if (request == null) {
            // 无效ip
            ip = "0.0.0.0";
        } else {
            ip = IpAddressUtils.getIpAdrress(request);
        }

        SysLog sysLog = new SysLog()
                .setOperationDescription(operationDescription)
                .setUsername(username)
                .setParams(params)
                .setMethodName(methodName)
                .setIp(ip);
        sysLogService.createSysLog(sysLog);
    }
}
